package cn.itrip.auth.service;

import cn.itrip.beans.pojo.ItripUser;
import cn.itrip.common.MD5;
import cn.itrip.common.RedisAPI;
import cn.itrip.dao.user.ItripUserMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author 瑾
 */
@Service("userService")
public class UserServiceImpl  implements  UserService{

    @Resource
    private ItripUserMapper itripUserMapper;

    @Resource(name = "mailService")
    private MailService mailService;

    @Resource(name = "smsService")
    private SmsService smsService;

    @Resource(name = "redisAPI")
    private RedisAPI redisAPI;

    /**
     *      手机短信码注册---
     * @param user
     * @throws Exception
     */
    @Override
    public void itriptxCreateUserByPhnoe(ItripUser user) throws Exception {
        //1 添加一条用户到数据库
        itripUserMapper.insertItripUser(user);

        //2  生成一个验证码(1111-9999)
        int code = MD5.getRandomCode();

        //3 发送验证码到手机上面
        // 模版  验证码 几分钟内有效
        smsService.send(user.getUserCode(),"1",new String[]{String.valueOf(code),"1"});


        //4 将验证码存入redis
        redisAPI.set("activation:"+user.getUserCode(),60,String.valueOf(code));


    }

    /**
     *  验证手机短信码 ，更新用户激活的状态
     */
    public boolean validatePhone(String phone,String code) throws Exception{
        //1 对比验证码
        String key = "activation:"+phone;
        String val = redisAPI.get(key);

        //用户输入的验证码和缓存验证码一致
        if(val!=null&&val.equals(code)){
            ItripUser user =this.findUserByUserCode(phone);
            if(user!=null){
                user.setFlatID(user.getId());
                user.setActivated(1);
                user.setUserType(0);
                itripUserMapper.updateItripUser(user);
                return true;
            }


        }



    return false;
    }

    /**
     * 注册一条用户
     * 1.添加用户信息
     * 2 生成激活码、
     * 3 发送邮件、
     * 4 激活码存入Redis
     * @param itripUser
     * @throws Exception
     */
    @Override
    public void itriptxCreateUserByEmail(ItripUser itripUser) throws Exception {
//        1.添加用户
        itripUserMapper.insertItripUser(itripUser);
        //2 生成激活码
        String activeCode = MD5.getMd5(new Date().toLocaleString(),32);

        //3 发送邮件
        mailService.sendActiveMail(itripUser.getUserCode(),activeCode);

        //4 激活码存入redis
        /*
         userCode---  手机号码 or 邮箱
        set重载， 作为临时有效key-value  key；用户名称 唯一性 30min  激活码
         */
        redisAPI.set("activation:"+itripUser.getUserCode(),30*60,activeCode);






    }
    /**
     *      1更新用户以及激活码的验证
     * @param mail  --userCode
     * @param code  激活码
     * @return
     * @throws Exception
     */
    @Override
    public boolean activateEmail(String mail, String code) throws Exception {
        //1 验证激活码
        String redisCode = redisAPI.get("activation:"+mail);

        //用户输入的激活码和redis缓存的激活码一致
        if(code.equals(redisCode)){
           Map<String,Object> map = new HashMap<String,Object>();
           map.put("userCode",mail);
            List<ItripUser> userList = new ArrayList<ItripUser>();
            userList = itripUserMapper.getItripUserListByMap(map);
            if(userList.size()>0){
                ItripUser user = userList.get(0);
                //2 更新用户
                user.setActivated(1);
                user.setUserType(0);  //0 代表自注册
                user.setFlatID(user.getId()); //平台 为自注册的主键ID
                itripUserMapper.updateItripUser(user);
                return true;//执行成功
            }else{
                return false;//执行失败
            }
        }else{
            return false;//执行失败
        }
    }

    @Override
    public ItripUser findUserByUserCode(String userCode) throws Exception {
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("userCode",userCode);
        List<ItripUser> list = new ArrayList<ItripUser>();
        list =   this.itripUserMapper.getItripUserListByMap(map);
        if(list.size()>0){
            return list.get(0);
        }
        return null;
    }







    /**
     * 用户名和密码的验证
     * @param userCode
     * @param userPassword
     * @return
     * @throws Exception
     */
    @Override
    public ItripUser login(String userCode, String userPassword) throws Exception {
        ItripUser user = null;
        user = this.findUserByUserCode(userCode);
        if(user!=null && user.getUserPassword().equals(userPassword)){
            if(user.getActivated()!=1){
                throw new Exception("用户未激活!");
            }
            return user;
        }else {
            return null;
        }


    }



}
